<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form isheader" v-if="headerShow">
        <a-form size="small" :model="pageData" layout="inline">
          <a-form-item label="保养人员">
            <a-input allow-clear :style="{ width: '200px' }" class="bacClass" placeholder="" v-model="dropDownData"
              @press-enter="huiche" />
          </a-form-item>
        </a-form>
        <div>
          <Toolbar :items="['查询', '新增', '删除']" @add="addHandler" @del="deleteHandler" @select="selectHandler">
          </Toolbar>
        </div>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18" />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>
    </template>
    <template #pageTabel>
      <!-- <a-tabs   :justify="true" default-active-key="1">
                <a-tab-pane key="1" title="保养类型列表"> -->
      <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true" rowSelection="multiple" @grid-ready="gridReady" style="height: 100%"
        :defaultColDef="defaultColDef" class="ag-theme-alpine" :rowData="tableDataList" :columnDefs="tc"
        :localeText="localeText1">
      </AgGridVuesCopys>
      <!-- </a-tab-pane>
            </a-tabs> -->
    </template>
    <paginationCopys :total="fySelet.total" show-total show-jumper show-page-size @change="PageSize"
      @page-size-change="change" style="justify-content: center" />

    <a-drawer style="z-index: 999" ok-text="保存" cancel-text="关闭" :drawer-style="{ zIndex: 9999 }" :mask-closable="false"
      :width="400" :ok-loading="pageData.pageLoading" :visible="showAdd" unmountOnClose @ok="addOk"
      @cancel="showAdd = false">
      <template #title>
        {{ sideTitle }}
      </template>
      <div>
        <a-form ref="formRef" :model="dataForm">
          <a-form-item label-col-flex="80px" label="保养人员" field="staffIdAndName"
            :rules="[{ required: true, message: '人员必填' }]" :validate-trigger="['change', 'blur']">
            <a-select popup-container="html"  :style="{ width: '250px' }" class="bacClass" v-model="dataForm.staffIdAndName" @click="byTypeClick"
              allow-clear allow-search>
              <a-option v-for="item in byTypeList" :value="item.id + '-' + item.name">{{
                item.name
              }}</a-option>
            </a-select>
          </a-form-item>
          <a-form-item label-col-flex="80px" label="机台类型" field="machineType"
            :rules="[{ required: true, message: '类型名称必填' }]" :validate-trigger="['change', 'blur']">
            <a-select popup-container="html"  :style="{ width: '250px' }" class="bacClass" v-model="dataForm.machineType" @click="byTypeClick2"
              allow-clear allow-search>
              <a-option v-for="item in byTypeList2" :value="item.machineTypeId + '-' + item.machineTypeName">{{
                item.machineTypeName }}</a-option>
            </a-select>
          </a-form-item>
          <a-form-item label-col-flex="80px" label="模板名称" field="keepTemplateName">
            <a-select popup-container="html"  :style="{ width: '250px' }" class="bacClass" v-model="dataForm.keepTemplateName"
              @click="byTypeClick3" allow-clear allow-search :disabled="!dataForm.machineType">
              <a-option v-for="item in byTypeList3">{{ item.keepTemplateName }}</a-option>
            </a-select>
          </a-form-item>
          <a-form-item label-col-flex="80px" label="机台名称" field="machineList"
            :rules="[{ required: true, message: '机台名称必填' }]" :validate-trigger="['change', 'blur']">
            <a-select popup-container="html"  :style="{ width: '250px' }" class="bacClass" v-model="dataForm.machineList" @click="macTypeClick"
              allow-clear allow-search multiple :disabled="!dataForm.machineType && !dataForm.keepTemplateName">
              <a-option v-for="item in macTypeList"
                :value="item.machineId + '-' + item.machineName + '-' + item.machineCode">{{ item.machineCode + '-' +
                  item.machineName }}</a-option>
            </a-select>
          </a-form-item>
        </a-form>
      </div>
    </a-drawer>
    <a-modal v-model:visible="visible" :width="300" :hide-cancel="true" ok-text="关闭" @ok="visible = false">
      <template #title> 机台明细 </template>
      <div class="mxClass">
        <div v-for="item in mxList">{{ item.machineCode + '_' + item.machineName }}</div>
      </div>
    </a-modal>
  </pageTabelLayout>
</template>

<script setup lang="ts">
import { post, get } from '@/api/http'
import { ref, reactive, onMounted, toRefs } from 'vue'
import Toolbar from '@/components/Toolbar.vue'

import { Message, Modal } from '@arco-design/web-vue'
import { localeText } from '@/api/aggridZw'
const localeText1: any = ref(localeText)

const headerShow = ref(true)

const pageData: any = reactive({
  dropDownData: '',
  showAdd: false,
  sideTitle: '',
})

const { dropDownData, showAdd, sideTitle } = toRefs(pageData)

const dataForm: any = reactive({
  id: null,
  staffName: '',
  staffId: null,
  staffIdAndName: null,
  machineType: '机台类型',
  keepTemplateName: '',
  machineList: [],
  machine: [],
})

function selectList() {
  post({
    url: 'zcTemRepair/keepMachineStaff/findKeepMachineStaff',
    data: {
      page: fySelet.page,
      limit: fySelet.size,
      staffName: pageData.dropDownData,
    },
  }).then((res: any) => {
    gridOption.value.setRowData(res.data.list)
    fySelet.total = res.data.total
  })
}

const huiche = () => { }

const selectHandler = () => {
  selectList()
}

const addHandler = () => {
  for (let i in dataForm) {
    dataForm[i] = ''
  }
  pageData.sideTitle = '新增设备绑定保养人员'
  pageData.showAdd = true
}

const deleteHandler = () => {
  if (gridOption.value.getSelectedRows().length === 0) {
    return false
  }
  Modal.confirm({
    title: '系统提示',
    content: '确认删除选中的数据?',
    onOk() {
      post({
        url: 'zcTemRepair/keepMachineStaff/deleteKeepMachineStaff',
        data: gridOption.value.getSelectedRows().map((o: any) => {
          return o.id
        }),
      }).then(({ code, data }: any) => {
        if (code === 200) {
          Message.success({
            content: '删除成功',
            duration: 5000,
          })
          fySelet.page = 1
          selectList()
        } else {
          Message.error({
            content: '删除失败',
            duration: 5000,
          })
        }
      })
    },
  })
}

const tableDataList: any = ref([])
const gridOption = ref()
const gridReady = (params: any) => {
  gridOption.value = params.api
}
const defaultColDef = {
  sortable: true,
  resizable: true,
  filter: true,
  flex: 1,
}

const fySelet: any = reactive({
  total: 10,
  size: 10,
  page: 1,
})

const PageSize = (val: any) => {
  fySelet.page = val
  selectList()
}

const change = (val: any) => {
  fySelet.size = val
  selectList()
}

const tc = [
  {
    showRowGroup: 'hide_def',
    headerName: '',
    checkboxSelection: true,
    headerCheckboxSelection: true,
    pinned: 'left',
    width: 50,
    resizable: false,
    filter: false,
    sortable: false,
    minWidth: 50,
    maxWidth: 50,
    lockPosition: 'left',
  },
  // {
  //     headerName: '序号',
  //     field: 'id',
  //     // pinned: o['fixed'],
  //     width: 150
  // },
  {
    headerName: '保养人员',
    field: 'staffName',
    width: 150,
  },
  {
    headerName: '机台',
    field: 'machine',
    width: 150,
    cellRenderer: {
      template: `
                        <a-space>
                          <a-tag class="tagCss"  @click="b">机台明细</a-tag>
                       </a-space>`,
      setup(props: any) {
        const b = () => {
          MacMxFun(props.params.data.machine)
        }
        return {
          b,
        }
      },
    },
  },
  {
    headerName: '创建人',
    field: 'createName',
    width: 150,
  },
  {
    headerName: '创建时间',
    field: 'createTime',
    width: 150,
  },
  {
    headerName: '最后修改人',
    field: 'updateName',
    width: 150,
  },
  {
    headerName: '最后修改时间',
    field: 'updateTime',
    width: 150,
  },
  {
    headerName: '操作',
    field: 'slot',
    pinned: 'right',
    width: 120,
    cellRenderer: {
      template: `
            <a-space>
                <a-tag class="tagCss" @click="a">修 改</a-tag>
            </a-space>
            `,
      setup(props: any) {
        const a = () => {
          updateList(props.params.data) // props.params.data
        }
        return {
          a,
        }
      },
    },
  },
]

const formRef: any = ref()

const addOk = () => {
  dataForm.machine = dataForm.machineList.map((res: any) => {
    return {
      machineId: Number(res.split('-')[0]),
      machineName: res.split('-')[1],
      machineCode: res.split('-')[2],
    }
  })
  if (pageData.sideTitle == '新增设备绑定保养人员') {
    formRef.value?.validate().then((err: any) => {
      if (!err) {
        post({
          url: 'zcTemRepair/keepMachineStaff/saveKeepMachineStaff',
          data: {
            staffName: dataForm.staffIdAndName.split('-')[1],
            staffId: Number(dataForm.staffIdAndName.split('-')[0]),
            machineType: dataForm.machineType.split('-')[1],
            machineTypeId: Number(dataForm.machineType.split('-')[0]),
            keepTemplateName: dataForm.keepTemplateName,
            machine: dataForm.machine,
          },
        }).then((res: any) => {
          if (res.code == 200) {
            Message.success('成功')
            pageData.showAdd = false
            selectList()
          } else {
            Message.error(res.message)
          }
        })
      }
    })
  } else {
    formRef.value?.validate().then((err: any) => {
      if (!err) {
        post({
          url: 'zcTemRepair/keepMachineStaff/updateKeepMachineStaff',
          data: {
            id: dataForm.id,
            staffName: dataForm.staffIdAndName.split('-')[1],
            staffId: Number(dataForm.staffIdAndName.split('-')[0]),
            machineType: dataForm.machineType.split('-')[1],
            machineTypeId: Number(dataForm.machineType.split('-')[0]),
            keepTemplateName: dataForm.keepTemplateName,
            machine: dataForm.machine,
          },
        }).then((res: any) => {
          if (res.code == 200) {
            Message.success('成功')
            pageData.showAdd = false
            selectList()
          } else {
            Message.error(res.message)
          }
        })
      }
    })
  }
}

const updateList = async (e: any) => {
  for (let i in e) {
    dataForm[i] = e[i]
  }
  dataForm.machineType = e.machineTypeId + '-' + e.machineType
  dataForm.staffIdAndName = dataForm.staffId + '-' + dataForm.staffName
  dataForm.machineList = e.machine.map((res: any) => {
    return res.machineId + '-' + res.machineName + '-' + res.machineCode
  })
  byTypeClick()
  macTypeClick()
  byTypeClick2()
  pageData.sideTitle = '修改设备绑定保养人员'
  pageData.showAdd = true
}

const byTypeList: any = ref([])

const byTypeClick = () => {
  post({
    url: 'admin/acl/user/findUserToken',
  }).then((res: any) => {
    if (res.code == 200) {
      if (res.data.data.departmentId == null || res.data.data.departmentId == 0) {
        Message.error('当前登陆账号无部门!')
        return
      }
      post({
        url: 'org/hrEmployee/getList',
        data: {
          deleteState: 0,
          obsoleteState: 0,
          department_id: res.data.data.departmentId,
        },
      }).then((resz: any) => {
        if (resz.code == 200) {
          byTypeList.value = resz.data
        } else {
          Message.error(resz.message)
        }
      })
    } else {
      Message.error(res.message)
    }
  })
}

const visible = ref(false)

const mxList: any = ref([])

const MacMxFun = (list: any) => {
  mxList.value = list
  visible.value = true
}

const byTypeList2: any = ref([])

const byTypeClick2 = () => {
  post({
    url: 'zcTemRepair/MachineTypeTemplate/selectMachineTypeName',
    data: {
      typeName: '',
    },
  }).then((res: any) => {
    if (res.code == 200) {
      byTypeList2.value = res.data.list
    } else {
      Message.error(res.message)
    }
  })
}

const byTypeList3: any = ref([])

const byTypeClick3 = () => {
  post({
    url: 'zcTemRepair/MachineTypeTemplate/selectMachineTypeTemplate',
    data: {
      machineTypeId: Number(dataForm.machineType.split('-')[0]),
    },
  }).then((res: any) => {
    if (res.code == 200) {
      byTypeList3.value = res.data.list
    } else {
      Message.error(res.message)
    }
  })
}

const macTypeList: any = ref([])

const macTypeClick = () => {
  post({
    url: 'zcTemRepair/machineTemplate/selectMachineTemplate',
    data: {
      machineTypeId: Number(dataForm.machineType.split('-')[0]),
      keepTemplateName: dataForm.keepTemplateName,
      machineTypeName: dataForm.machineType.split('-')[1],
    },
  }).then((res: any) => {
    if (res.code == 200) {
      macTypeList.value = res.data.list
    } else {
      Message.error(res.message)
    }
  })
}
</script>
<style scoped lang="less">
:deep(.ag-cell-value) {
  user-select: initial;
  -moz-user-select: text;
  -ms-user-select: text;
  -webkit-user-select: text;
}

:deep(.arco-table-td-content) {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

:deep(.ag-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
  border-right: 1px solid #dde2eb;
}

.mxClass {
  width: 100%;

  div {
    width: 100%;
    text-align: center;
    height: 50px;
    font-family: Microsoft Yahei;
    font-weight: 600;
    font-size: 16px;
  }
}
</style>
